package com.yang.service.Impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.constants.SystemConstants;
import com.yang.domain.DTO.AddRoleDto;
import com.yang.domain.DTO.ChangeRoleStatusDto;
import com.yang.domain.DTO.UpdateRoleDto;
import com.yang.domain.Result;
import com.yang.domain.VO.PageVo;
import com.yang.domain.entity.Role;
import com.yang.domain.entity.RoleMenu;
import com.yang.mapper.RoleMapper;
import com.yang.service.RoleMenuService;
import com.yang.service.RoleService;
import com.yang.utils.BeanCopyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 角色表(Role)表服务实现类
 * </p>
 * @author yang
 * @date 2023/5/29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMenuService roleMenuService;
    @Override
    public List<String> selectRoleKeyByUserId(Long userId) {
        //1.判断是否是管理员 如果是返回集合中只需要有admin
        if(userId == 1L){
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }
        //否则查询用户所具有的角色信息
        return getBaseMapper().selectRoleKeyByUserId(userId);
    }

    @Override
    public PageVo selectRolePage(Role role, Integer pageNum, Integer pageSize) {

        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(StringUtils.hasText(role.getRoleName()),Role::getRoleName,role.getRoleName());
        wrapper.eq(StringUtils.hasText(role.getStatus()),Role::getStatus,role.getStatus());
        wrapper.orderByAsc(Role::getRoleSort);

        Page<Role> page = new Page<>(pageNum,pageSize);
        page(page,wrapper);

        return new PageVo(page.getRecords(),page.getTotal());
    }

    @Override
    public Result changeStatus(ChangeRoleStatusDto dto) {

        Role role = new Role();
        role.setId(dto.getRoleId());
        role.setStatus(dto.getStatus());

        boolean success = updateById(role);

        if (!success){
            throw new RuntimeException("修改用户状态失败，请联系管理员");
        }

        return Result.okResult();
    }

    @Override
    public Result addRole(Role role) {
        save(role);

        if(role.getMenuIds()!=null&&role.getMenuIds().length>0){
            insertRoleMenu(role);
        }
        return Result.okResult();
    }

    @Override
    @Transactional
    public Result updateRole(UpdateRoleDto updateRoleDto) {

        Role role = BeanCopyUtils.copyBean(updateRoleDto, Role.class);

        //1.修改角色信息
        updateById(role);

        //2.删除角色菜单关联表
        roleMenuService.deleteRoleMenuByRoleId(role.getId());

        //3.重新添加角色菜单关联表
        insertRoleMenu(role);

        return Result.okResult();
    }

    @Override
    public List<Role> selectRoleAll() {
        return list(Wrappers.<Role>lambdaQuery().eq(Role::getStatus, SystemConstants.NORMAL));
    }

    @Override
    public List<Long> selectRoleIdByUserId(Long userId) {
        return getBaseMapper().selectRoleIdByUserId(userId);
    }

    private void insertRoleMenu(Role role) {

        List<RoleMenu> roleMenuList = Arrays.stream(role.getMenuIds())
                                            .map(menuId -> new RoleMenu(role.getId(),menuId))
                                            .collect(Collectors.toList());

        roleMenuService.saveBatch(roleMenuList);

//        for (Long menuId : role.getMenuIds()) {
//            RoleMenu roleMenu = new RoleMenu(role.getId(),menuId);
//            roleMenuService.save(roleMenu);
//        }
    }
}
